package com.cooper.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * 随机密码生成器
 * @Title: RandomPassword.java<br>
 * @Date: Nov 12, 2011 7:23:34 PM<br>
 * @Copyright (c) 2011 MiXuan <br> * 
 * @since 1.0
 * @author coraldane
 */
public class RandomPassword {
	
	private static final Logger log = LogManager.getLogger(RandomPassword.class);
	private static final List<Character> pwdCharList = new ArrayList<Character>();
	
	static{
		for(char index = '0'; index < '9'; index ++){
			pwdCharList.add(index);
		}
		for(char index = 'a'; index < 'z'; index ++){
			pwdCharList.add(index);
		}
		for(char index = 'A'; index < 'Z'; index ++){
			pwdCharList.add(index);
		}
	}
	
	/**
	 * 生成随机密码，密码长度为6 -20之间的随机值
	 * @return
	 * @date Nov 12, 2011 7:27:15 PM
	 * @author coraldane
	 */
	public String doGenerate(){
		double dv = Math.random() * 14;
		int length = new Double(dv).intValue() + 6;
		return this.doGenerate(length);
	}
	
	/**
	 * 生成随机密码
	 * @param length 随机密码的长度
	 * @return
	 * @date Nov 12, 2011 7:26:50 PM
	 * @author coraldane
	 */
	public String doGenerate(int length){
		StringBuffer buffer = new StringBuffer();
		Random rand = new Random();
		int size = pwdCharList.size();
		for(int index =0; index < length; index ++){
			int rd = rand.nextInt(size);
			buffer.append(pwdCharList.get(rd));
		}
		log.debug("Random Password's length is:" + length +",value:" + buffer);
		return buffer.toString();
	}
	
	public static void main(String[] args){
		RandomPassword rp = new RandomPassword();
		System.out.println(rp.doGenerate(6));
	}
}
